// 主路由文件
const express = require('express');
const router = express.Router();
const sequelize = require('../config/database');

// 导入子路由
const userRoutes = require('./userRoutes');
const classRoutes = require('./classRoutes');
const homeworkRoutes = require('./homeworkRoutes');
const submissionRoutes = require('./submissionRoutes');

/**
 * 路由配置
 * 整合所有API端点
 */

// 用户相关路由
router.use('/api/users', userRoutes);

// 班级相关路由
router.use('/api/classes', classRoutes);

// 作业相关路由
router.use('/api/homeworks', homeworkRoutes);

// 作业提交相关路由
router.use('/api/submissions', submissionRoutes);

// 健康检查路由 - 测试数据库连接
router.get('/api/health/check-db', async (req, res) => {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    
    // 可选：测试数据库查询
    const [result] = await sequelize.query('SELECT 1 AS connection_test');
    
    res.json({
      success: true,
      message: '数据库连接成功',
      data: {
        connectionStatus: 'connected',
        timestamp: new Date().toISOString(),
        queryResult: result[0] || null
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '数据库连接失败',
      error: {
        message: error.message,
        type: error.name,
        code: error.constructor.name
      },
      timestamp: new Date().toISOString()
    });
  }
});

// 根路由
router.get('/', (req, res) => {
  res.json({
    success: true,
    message: '学生作业提交系统后端API',
    version: '1.0.0',
    availableEndpoints: [
      '/api/health/check-db - 测试数据库连接'
    ]
  });
});

module.exports = router;